<script setup lang="ts">
import { getCheckedList } from '@/utils'
import SubCheckListItem from '@/views/console/system/components/SubCheckListItem.vue'
import { onMounted, ref, watch } from 'vue'
import type { OMenuListGetItem } from '@/typed/response'

interface IProps {
	data: OMenuListGetItem[]
	checkedList?: any[];
	admin: boolean;
}

const emit = defineEmits(['change'])
const props = withDefaults(defineProps<IProps>(), {});
const dataList = ref<any[]>([])

onMounted(() => {
	initData()
})

watch(() => props.data, () => {
	initData()
})
watch(() => props.checkedList, () => {
	initData()
})
watch(() => JSON.stringify(dataList.value), () => {
	let hasChange = false;
	let newList = dataList.value.map(i => {
		let result = getCheckedList(i.children)
		let indeterminate = result.checked.length > 0 && result.checked.length !== result.all.length
		let subChecked = result.checked.length > 0
		if (indeterminate !== i.indeterminate || i.checked !== subChecked) {
			hasChange = true;
		}
		return {
			...i,
			checked: subChecked,
			indeterminate
		}
	})

	if (hasChange) {
		dataList.value = newList;
	} else {
		emit('change', dataList.value)
	}
})

function initData() {
	dataList.value = setChecked(props.data)
}


function setChecked(list: any[], checkedAll?: boolean): any[] {
	return list.map(({ children, ...other }: any) => {
		const checked = checkedAll === undefined ? props.admin || props.checkedList?.includes(other.menuId) : checkedAll;
		const child = setChecked(children || [], checkedAll);
		const result = getCheckedList(child)
		return {
			disabled: !props.checkedList,
			...other,
			checked,
			indeterminate: result.checked.length > 0 && result.checked.length !== result.all.length,
			...(children ? { children: child } : {})
		}
	})
}

function selectAll(index: number) {
	const newItem = { ...dataList.value[index] }
	newItem.children = setChecked(newItem.children, newItem.checked)
	newItem.indeterminate = false;
	dataList.value.splice(index, 1, newItem)
}
</script>
<template>
	<SubCheckListItem
		:data="dataList"
		:admin="admin"
		@select-all="selectAll"
	/>
</template>
<style lang="less" scoped>
</style>
